import { coverContent } from '../helper'
import { ConverContentProps, MessageContent, UniversalProps } from '../type'
import { BaseProvider } from './base-provider'
import { ChatCompletion } from '@baiducloud/qianfan'
export class QianfanProvider extends BaseProvider {
  private client: any
  constructor(accessKey: string, secretKey: string) {
    super()
    this.client = new ChatCompletion({
      QIANFAN_ACCESS_KEY: accessKey,
      QIANFAN_SECRET_KEY: secretKey,
      ENABLE_OAUTH: false
    })
  }
  async chat(message: ConverContentProps, model: string): Promise<any> {
    const coverMessage = await coverContent(message)
    const stream = await this.client.chat(
      {
        messages: coverMessage,
        stream: true
      },
      model
    )
    const self = this
    return {
      async *[Symbol.asyncIterator]() {
        for await (const part of stream) {
          yield self.transformResponse(part)
        }
      }
    }
  }
  protected transformResponse(chunk: any): UniversalProps {
    const { is_end, result } = chunk
    return {
      is_end,
      result
    }
  }
}
